#include <android/native_window_jni.h>
#include <android/native_window.h>
#include <media/NdkMediaExtractor.h>
#include <media/NdkMediaFormat.h>
#include <media/NdkMediaCodec.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

// 缓冲区大小，可根据实际情况调整
#define BUFFER_SIZE 4096

// 函数接收一个URL字符串参数，用于播放对应流媒体内容
void playStreamingMedia(const char* streamUrl) {
    // 创建MediaExtractor实例
    AMediaExtractor* extractor = AMediaExtractor_new();
    if (extractor == NULL) {
        return;
    }
    media_status_t status = AMediaExtractor_setDataSource(extractor, streamUrl);
    if (status!= AMEDIA_OK) {
        AMediaExtractor_delete(extractor);
        return;
    }

    // 查找音频轨道索引
    int32_t numTracks = AMediaExtractor_getTrackCount(extractor);
    int audioTrackIndex = -1;
    for (int i = 0; i < numTracks; ++i) {
        AMediaFormat* format = AMediaExtractor_getTrackFormat(extractor, i);
        const char* mime;
        AMediaFormat_getString(format, AMEDIAFORMAT_KEY_MIME,&mime);
        if (mime!= NULL && strcmp(mime, "audio/mp4a-latm") == 0) {  // 这里以常见的AAC编码格式判断为例，可根据实际扩展
            audioTrackIndex = i;
            break;
        }
        AMediaFormat_delete(format);
    }
    if (audioTrackIndex == -1) {
        AMediaExtractor_delete(extractor);
        return;
    }

    // 选择音频轨道
    AMediaExtractor_selectTrack(extractor, audioTrackIndex);

    // 获取音频格式相关参数
    AMediaFormat* audioFormat = AMediaExtractor_getTrackFormat(extractor, audioTrackIndex);
    int sampleRate;
    int channelCount;
    int bitsPerSample;
    AMediaFormat_getInt32(audioFormat, AMEDIAFORMAT_KEY_SAMPLE_RATE, &sampleRate);
    AMediaFormat_getInt32(audioFormat, AMEDIAFORMAT_KEY_CHANNEL_COUNT, &channelCount);
    AMediaFormat_getInt32(audioFormat, AMEDIAFORMAT_KEY_BIT_RATE, &bitsPerSample);
    AMediaFormat_delete(audioFormat);

    // 缓冲区，用于存储从媒体流中读取的音频数据
    uint8_t buffer[BUFFER_SIZE];
    size_t readSize;
    while ((readSize = AMediaExtractor_readSampleData(extractor, buffer, BUFFER_SIZE)) > 0) {
        AMediaExtractor_advance(extractor);
    }

    // 停止并释放资源
    AMediaExtractor_delete(extractor);
}
